package cn.iocoder.yudao.module.reading.convert.community;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.reading.controller.app.community.vo.post.PostCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.community.vo.post.PostRespVO;
import cn.iocoder.yudao.module.reading.controller.app.community.vo.post.PostUpdateReqVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.community.CommunityPostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.util.List;

/**
 * 社区帖子 Convert
 *
 * @author 芋道源码
 */
@Mapper
public interface CommunityPostConvert {

    CommunityPostConvert INSTANCE = Mappers.getMapper(CommunityPostConvert.class);

    ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 转换为帖子DO
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "userId", ignore = true)
    @Mapping(target = "likeCount", constant = "0")
    @Mapping(target = "commentCount", constant = "0")
    @Mapping(target = "viewCount", constant = "0")
    @Mapping(target = "isTop", constant = "false")
    @Mapping(target = "isHot", constant = "false")
    @Mapping(target = "status", constant = "1")
    CommunityPostDO convert(PostCreateReqVO reqVO);

    /**
     * 转换为帖子DO（更新）
     */
    @Mapping(target = "userId", ignore = true)
    @Mapping(target = "type", ignore = true)
    @Mapping(target = "workId", ignore = true)
    @Mapping(target = "workType", ignore = true)
    @Mapping(target = "likeCount", ignore = true)
    @Mapping(target = "commentCount", ignore = true)
    @Mapping(target = "viewCount", ignore = true)
    @Mapping(target = "isTop", ignore = true)
    @Mapping(target = "isHot", ignore = true)
    @Mapping(target = "status", ignore = true)
    CommunityPostDO convert(PostUpdateReqVO reqVO);

    /**
     * 转换为帖子响应VO
     */
    default PostRespVO convert(CommunityPostDO postDO, AdminUserDO userDO, Boolean isLiked) {
        if (postDO == null) {
            return null;
        }

        PostRespVO respVO = new PostRespVO();
        respVO.setId(postDO.getId());
        respVO.setUserId(postDO.getUserId());
        respVO.setType(postDO.getType());
        respVO.setTitle(postDO.getTitle());
        respVO.setContent(postDO.getContent());
        respVO.setWorkId(postDO.getWorkId());
        respVO.setWorkType(postDO.getWorkType());
        respVO.setLikeCount(postDO.getLikeCount());
        respVO.setCommentCount(postDO.getCommentCount());
        respVO.setViewCount(postDO.getViewCount());
        respVO.setIsTop(postDO.getIsTop());
        respVO.setIsHot(postDO.getIsHot());
        respVO.setCreateTime(postDO.getCreateTime());
        respVO.setUpdateTime(postDO.getUpdateTime());
        respVO.setIsLiked(isLiked != null ? isLiked : false);

        // 转换JSON字段
        if (postDO.getImages() != null) {
            try {
                respVO.setImages(OBJECT_MAPPER.readValue(postDO.getImages(), new TypeReference<List<String>>() {}));
            } catch (Exception e) {
                // 忽略JSON解析错误
            }
        }

        // 设置用户信息
        if (userDO != null) {
            respVO.setUserNickname(userDO.getNickname());
            respVO.setUserAvatar(userDO.getAvatar());
        }

        return respVO;
    }

    /**
     * 转换为帖子响应VO（支持reading模块用户）
     */
    default PostRespVO convert(CommunityPostDO postDO, UserDO userDO, Boolean isLiked) {
        return convert(postDO, userDO, isLiked, null);
    }

    /**
     * 转换为帖子响应VO（支持reading模块用户，带URL转换）
     */
    default PostRespVO convert(CommunityPostDO postDO, UserDO userDO, Boolean isLiked, StaticResourceUrlUtils urlUtils) {
        if (postDO == null) {
            return null;
        }

        PostRespVO respVO = new PostRespVO();
        respVO.setId(postDO.getId());
        respVO.setUserId(postDO.getUserId());
        respVO.setType(postDO.getType());
        respVO.setTitle(postDO.getTitle());
        respVO.setContent(postDO.getContent());
        respVO.setWorkId(postDO.getWorkId());
        respVO.setWorkType(postDO.getWorkType());
        respVO.setLikeCount(postDO.getLikeCount());
        respVO.setCommentCount(postDO.getCommentCount());
        respVO.setViewCount(postDO.getViewCount());
        respVO.setIsTop(postDO.getIsTop());
        respVO.setIsHot(postDO.getIsHot());
        respVO.setCreateTime(postDO.getCreateTime());
        respVO.setUpdateTime(postDO.getUpdateTime());
        respVO.setIsLiked(isLiked != null ? isLiked : false);

        // 转换JSON字段
        if (postDO.getImages() != null) {
            try {
                respVO.setImages(OBJECT_MAPPER.readValue(postDO.getImages(), new TypeReference<List<String>>() {}));
            } catch (Exception e) {
                // 忽略JSON解析错误
            }
        }

        // 设置用户信息
        if (userDO != null) {
            respVO.setUserNickname(userDO.getNickname());
            // 处理用户头像URL转换
            if (urlUtils != null && userDO.getAvatar() != null) {
                respVO.setUserAvatar(urlUtils.toFullUrl(userDO.getAvatar()));
            } else {
                respVO.setUserAvatar(userDO.getAvatar());
            }
        }

        return respVO;
    }

    /**
     * 转换为帖子响应VO列表
     */
    default List<PostRespVO> convertList(List<CommunityPostDO> postList, List<AdminUserDO> userList, List<Boolean> likedList) {
        if (postList == null) {
            return null;
        }

        return postList.stream().map(post -> {
            AdminUserDO user = userList.stream()
                    .filter(u -> u.getId().equals(post.getUserId()))
                    .findFirst()
                    .orElse(null);

            Boolean isLiked = likedList != null && likedList.size() > postList.indexOf(post)
                    ? likedList.get(postList.indexOf(post))
                    : false;

            return convert(post, user, isLiked);
        }).toList();
    }

    /**
     * 转换分页结果
     */
    default PageResult<PostRespVO> convertPage(PageResult<CommunityPostDO> pageResult, List<AdminUserDO> userList, List<Boolean> likedList) {
        if (pageResult == null) {
            return null;
        }

        PageResult<PostRespVO> result = new PageResult<>();
        result.setTotal(pageResult.getTotal());
        result.setList(convertList(pageResult.getList(), userList, likedList));
        return result;
    }

    /**
     * 将图片列表转换为JSON字符串
     */
    default String convertImagesToJson(List<String> images) {
        if (images == null || images.isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(images);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将JSON字符串转换为图片列表
     */
    default List<String> convertJsonToImages(String json) {
        if (json == null || json.trim().isEmpty()) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<List<String>>() {});
        } catch (Exception e) {
            return null;
        }
    }

}
